package com.supreme.nettyapp.generalserver.echoserver.service;

import com.supreme.nettyapp.generalserver.echoserver.handler.EchoServerInitializer;
import com.supreme.nettyapp.generalserver.echoserver.props.EchoServerProps;
import com.supreme.nettyapp.generalserver.service.NettyServerService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class EchoServerService implements NettyServerService {

    @Resource
    private EchoServerProps echoServerProps;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private Channel serverChannel;

    @Async(value = "nettyTask")
    @Override
    public void startNettyServer() {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(EchoServerInitializer.INSTANCE);

            // Start the server.
            Integer serverPort = echoServerProps.getPort();
            ChannelFuture channelFuture = serverBootstrap.bind(serverPort).sync();

            // Wait until the server socket is closed.
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Override
    public void destroyNettyServer() {
        try {
            serverChannel.close().sync();
        } catch (InterruptedException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        } finally {
            Optional.ofNullable(bossGroup).ifPresent(EventExecutorGroup::shutdownGracefully);
            Optional.ofNullable(workerGroup).ifPresent(EventExecutorGroup::shutdownGracefully);
        }

    }
}
